﻿using System;
using System.Globalization;
using System.Web.UI.WebControls;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.TimesheetManagement
{
    public partial class UpdateTimesheet : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();
            if (!IsPostBack)
            {
                BindDataGrid();
                BindDataContractNumber();
            }
        }
        // bind data on grid timesheet
        protected void BindDataGrid()
        {
            var id = Request.QueryString["id"].ToString(CultureInfo.InvariantCulture);
            var result = TimesheetLogic.SelectTimesheetDetailByTimesheetDetailId(id);
            GridViewTimesheet.DataSource = result;
            GridViewTimesheet.DataBind();
        }
        //bind data contract number on dropdownlist contract 
        protected void BindDataContractNumber()
        {
            var id = Request.QueryString["id"].ToString(CultureInfo.InvariantCulture);
            var result = TimesheetLogic.SelectTimesheetDetailByTimesheetDetailId(id);
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var dropDownListContractNumber = (DropDownList)row.FindControl("DropDownListContractNumber");
                    dropDownListContractNumber.DataSource = result;
                    dropDownListContractNumber.DataTextField = "ContractNumber";
                    dropDownListContractNumber.DataValueField = "ContractNumber";
                    dropDownListContractNumber.DataBind();
                }
            }
        }
        //check null item of gridview
        protected bool CheckItemGrid()
        {
            labelResultMessage.Visible = true;
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var textDate = (TextBox)row.FindControl("textDate");
                    var textTime = ((TextBox)row.FindControl("textTime"));
                    var textDescription = (TextBox)row.FindControl("textDescription");

                    if (string.IsNullOrEmpty(textDate.Text))
                    {
                        labelResultMessage.Text = "Please choose On Date";
                        textDate.CssClass = "CPF-input-error";
                        textDate.Focus();
                        return false;
                    }
                    if (!string.IsNullOrEmpty(textTime.Text))
                    {
                        if (string.IsNullOrEmpty(textDescription.Text))
                        {
                            labelResultMessage.Text = "Please enter description";
                            textDescription.CssClass = "CPF-input-error";
                            textDescription.Focus();
                            return false;
                        }
                        var time = float.Parse((textTime.Text),CultureInfo.InvariantCulture);
                        if (time < 0 || time > 24)
                        {
                            labelResultMessage.Text = "Time between 1 and 24";
                            textTime.CssClass = "CPF-input-error";
                            textTime.Focus();
                            return false;
                        }
                    }
                    if (!string.IsNullOrEmpty(textDescription.Text))
                    {
                        if (string.IsNullOrEmpty(textTime.Text))
                        {
                            labelResultMessage.Text = "Please enter time";
                            textTime.CssClass = "CPF-input-error";
                            textTime.Focus();
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        //button update timesheet
        protected void ButtonUpdateTimesheet(object sender, EventArgs e)
        {
            labelResultMessage.Text = string.Empty;

            if (!CheckItemGrid())
                return;
            foreach (GridViewRow row in GridViewTimesheet.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    var id = Request.QueryString["id"].ToString(CultureInfo.InvariantCulture);
                    var textDate = (TextBox) row.FindControl("textDate");
                    var textTime = ((TextBox) row.FindControl("textTime"));
                    var textDescription = (TextBox) row.FindControl("textDescription");
                    var dropDownListContractNumber = (DropDownList)row.FindControl("DropDownListContractNumber");
                    
                    var timesheet = new TimesheetDetailEntity
                                        {
                                            TimesheetDetailId = int.Parse((id),CultureInfo.InvariantCulture),
                                            ContractNumber = dropDownListContractNumber.SelectedValue,
                                            OnDate = DateTime.Parse(textDate.Text, CultureInfo.InvariantCulture),
                                            Time = float.Parse((textTime.Text),CultureInfo.InvariantCulture),
                                            Description = textDescription.Text
                                        };
                    var result = TimesheetLogic.UpdateTimesheet(timesheet);
                    if (result != "Successfully!")
                    {
                        labelResultMessage.Visible = true;
                        labelResultMessage.Text = "Update timesheet failed";

                        // Save event of logging out
                        var userEventEntity = new EventEntity
                        {
                            UserName = CommonLogic.ConvertToString(Session["UserName"]),
                            OnDate = DateTime.Now,
                            EventType = (int)EventTypeList.UserEvent,
                            Description = "User logged out"
                        };

                        EventTracer.SaveEvents(userEventEntity);
                        return;
                    }
                    //if result == "Successfully!" then successfull, redirect to page ListTimesheet.aspx
                    labelResultMessage.Text = "Insert Success";
                    Response.Redirect("ListTimesheet.aspx");
                }
            }
        }

        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.UpdateTimesheet;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }
    }
}

